package com.qf.blog.controller.system;

import com.alibaba.fastjson.JSON;
import com.qf.blog.core.constants.BaseConstants;
import com.qf.blog.core.servlet.BaseServlet;
import com.qf.blog.entity.SystemUserEntity;
import com.qf.blog.service.SystemUserService;
import org.springframework.context.ApplicationContext;
import javax.servlet.annotation.WebServlet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zyt
 * @version 1.0
 */
@WebServlet("/SystemUserServlet/*")
public class SystemUserServlet extends BaseServlet {
    //创建业务层对象
//    private SystemUserService systemUserService= new SystemUserServiceImpl();
    //现在只是声明
    private  SystemUserService systemUserService;
    //在上下文中获取IOC容器 ，从容器中获取service给上面赋值
    // spring工厂在上下文对象中
    @Override
    public void myInit(){
        //获取上下文对象.getAttribute() 方法通过key拿到value
        ApplicationContext a = (ApplicationContext) this.req.getServletContext().getAttribute("spring");
        // 现在这一步给上面的systemUserService实例化
        systemUserService=a.getBean("systemUserService",SystemUserService.class);
    }
    // list查询的方法
    public  void list()throws Exception{
        // 1. 查询数据
        List<SystemUserEntity> list = systemUserService.list();
        // 2. 把数据放到map中
        Map<String,Object> map = new HashMap<>();
        map.put("sysUserlist",list);
        // 3. 跳转视图
        outView("system/sysUser/sysUserList", map);
    }
    public String add() throws Exception {
        String json = super.req.getReader().readLine();
        System.out.println(json);
        SystemUserEntity systemUserEntity = JSON.parseObject(json, SystemUserEntity.class);
        boolean save = systemUserService.save(systemUserEntity);
        return outJson(save);
    }

    public void systemUserById() throws Exception {
        String id = this.req.getParameter("id");
        SystemUserEntity systemUserEntity = systemUserService.byId(Integer.parseInt(id));
        Map<String, Object> map = new HashMap<>();
        map.put("systemUserEntity", systemUserEntity);
        outView("/system/sysUser/sysUserUpdate", map);
    }

    public String update() throws Exception {
        String json = super.req.getReader().readLine();
        SystemUserEntity systemUserEntity = JSON.parseObject(json, SystemUserEntity.class);
        boolean save = systemUserService.update(systemUserEntity);
        return outJson(save);
    }

    public String delete() throws Exception {
        String id = super.req.getParameter("id");
        boolean remove = systemUserService.remove(Integer.parseInt(id));
        return BaseConstants.BASE_REDIRECT + ":" + "SystemUserServlet/list";
    }

    public String batchDel() throws Exception {
        String json = req.getReader().readLine();
        List<Integer> list = JSON.parseArray(json, Integer.class);
        return outJson(systemUserService.batchRemove(list));
    }

}
